// pages/goods/date-picker/date-picker.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    title: {
      type: String,
      value: "请选择时间"
    },
    visible: {
      type: Boolean,
      value: false,
      observer: "onVisible"
    },
    // 日期列表
    list: {
      type: Array,
      value: [],
      observer: "onList"
    },
    // 选中的日期下标
    selected: {
      type: Array,
      value: [],
      observer: "onSelected"
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    dateList: [],
    prevSelected: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onList() { },
    onSelected() { },
    // 监听visible变化
    onVisible() {
      let strList = JSON.stringify(this.data.list);
      let dateList = JSON.parse(strList);
      let selected = this.data.selected;

      selected.forEach(v => {
        dateList[v].value = 0;
      })

      this.setData({
        dateList,
        prevSelected: selected.slice()
      });

    },
    // 触摸遮罩层
    onTouchMask: function () {
      this.triggerEvent("TouchMask", {
        selected: this.data.selected
      });
    },
    // 确认
    onSubmit() {
      this.triggerEvent("TapSubmit", {
        selected: this.data.selected
      });
    },
    // 取消
    onCancel() {
      console.log("prev => ", this.data.prevSelected);
      this.triggerEvent("TapCancel", {
        selected: this.data.prevSelected
      });
    },
    // 切换状态
    onTrigger(e) {
      let index = e.currentTarget.dataset.index;
      let item = this.data.dateList[index];
      let dateList = this.data.dateList;
      let selected = this.data.selected;

      // console.log("[ before ] selected => ", selected);

      if (item.value == -1) {
        return;
      }

      if (item.value == 1) {
        item.value = 0;
        selected.push(index);
      } else if (item.value == 0) {
        item.value = 1;
        selected.forEach((v, i) => {
          if (v == index) {
            selected.splice(i, 1);
            return;
          }
        })
      }
      dateList[index] = item;

      this.setData({
        dateList,
        selected
      })

      // console.log("[ after ] selected => ", selected);
    },

  }
})